import Banner from "./Banner";
import { BundleManager } from "./BundleManager";
import EndingAnimation from "./EndingAnimation";
import EndTalk from "./Gwx/EndTalk";
import Ending, { End } from "./Gwx/Ending";
import SharkSayManager, { SharkSayType } from "./SharkSayManager";
import Tween_breathe from "./Tween/Tween_breathe";
import WTool from "./WTool";

const { ccclass, property } = cc._decorator;

export enum SharkAnim {
    Anim_哑铃 = "哑铃",
    Anim_睡觉 = "睡觉",
    Anim_叉眼 = "叉眼",
    Anim_哭脸 = "哭脸",
    Anim_正常脸 = "正常脸",
    Anim_正常脸汗 = "正常脸汗",
    Anim_皱眉说 = "皱眉说",
    Anim_笑说 = "笑说",
    Anim_闭眼泪 = "闭眼泪",
    Anim_惊讶 = "惊讶",
    Anim_默认笑 = "默认笑",
    Anim_默认皱眉 = "默认皱眉",
}

@ccclass
export default class GameManager extends cc.Component {
    @property(cc.JsonAsset)
    SayDate: cc.JsonAsset = null;
    @property(cc.Node)
    GameNode: cc.Node = null;
    @property(cc.Node)
    UINode: cc.Node = null;
    @property(cc.Node)//鲨鱼节点
    SharkNode: cc.Node = null;
    @property(cc.AudioClip)//默认音效
    defaultaudio: cc.AudioClip = null;
    public GamePause: boolean = false;//游戏暂停
    public static SharkHurted: boolean = false;//小鲨鱼是否被伤害过
    public sharkData: number[] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];//0.鲨鱼大小1.锻炼次数2.睡觉次数3.是否吊胃口4.吊胃口是否被中断5.身上是否有带花6.是否被食人花吃了
    //7.是否关灯过8.害怕是否被中断9.是否变成了无用10.默认是笑还是皱眉(0笑1皱眉)
    public static EndData: number[] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];//0-结局未达成，1-结局达成
    private static _instance: GameManager = null;
    public static get Instance(): GameManager {
        if (!this._instance) {
            this._instance = new GameManager();
        }
        return this._instance;
    }

    Anim: cc.Animation = null;//小鲨鱼的动画组件
    cb: Function = null;//流浪鲨鱼事件回调

    protected onLoad(): void {
        GameManager._instance = this;
        this.Anim = this.SharkNode.getComponent(cc.Animation);
    }

    start() {
        this.Init();
        if (!Banner.IsBlackWhite) {//正常包模式
            Banner.Instance.ShowNativeAd();
            Banner.Instance.ShowBanner();
        } else {//黑白包模式
            if (Banner.cityIswhite) {//黑包
                Banner.Instance.ShowNativeAd();
                Banner.Instance.ShowBanner();
                Banner.Instance.ShowVideo(() => { });
            } else {//白包
                Banner.Instance.ShowNativeAd();
                Banner.Instance.ShowBanner();
            }
        }
        this.ChanggeSharkSize(0);
    }

    //初始化户外场景
    Init() {
        if (GameManager.Instance.GetEndingIsFinish(End.结局3) == 1 ||
            GameManager.Instance.GetEndingIsFinish(End.结局4) == 1 ||
            GameManager.Instance.GetEndingIsFinish(End.结局5) == 1 ||
            GameManager.Instance.GetEndingIsFinish(End.结局8) == 1 ||
            GameManager.Instance.GetEndingIsFinish(End.结局10) == 1) {
            //小鲨鱼受过伤害
            GameManager.SharkHurted = true;
            this.LoadSpriteFrame("Sprits", "黄昏", (spf) => {
                GameManager.GetNode("outdoor/室外").getComponent(cc.Sprite).spriteFrame = spf;
            })
            this.LoadSpriteFrame("Sprits", "黄昏地", (spf) => {
                GameManager.GetNode("outdoor/室外上草地").getComponent(cc.Sprite).spriteFrame = spf;
            })
            this.LoadSpriteFrame("Sprits", "黄昏大云", (spf) => {
                GameManager.GetNode("outdoor/大云").getComponent(cc.Sprite).spriteFrame = spf;
            })
            this.LoadSpriteFrame("Sprits", "黄昏小云", (spf) => {
                GameManager.GetNode("outdoor/小云").getComponent(cc.Sprite).spriteFrame = spf;
            })
        }
        if (this.GetEndingIsFinish(End.结局3) == 1) {//小鲨鱼离家出走了
            if (this.GetEndingIsFinish(End.结局7) == 0 && this.GetEndingIsFinish(End.结局9) == 0) {//小鲨鱼是否被叫回家
                //小鲨鱼依然流浪着
                let liulang = GameManager.GetNode("outdoor/流浪鲨鱼");
                liulang.active = true;
                this.scheduleOnce(() => {
                    liulang.getComponent(Tween_breathe).resetTween(1.2);
                })
                GameManager.Instance.LoadSpriteFrame("Sprits", "红框", (spf) => {
                    GameManager.GetUINode("StarPanel/放弃框").getComponent(cc.Sprite).spriteFrame = spf;
                })
                let spf = GameManager.GetUINode("StarPanel/放弃框/取消").getComponent(cc.Sprite).spriteFrame;
                GameManager.GetUINode("StarPanel/放弃框/取消").getComponent(cc.Sprite).spriteFrame = GameManager.GetUINode("StarPanel/放弃框/是的").getComponent(cc.Sprite).spriteFrame;
                GameManager.GetUINode("StarPanel/放弃框/是的").getComponent(cc.Sprite).spriteFrame = spf;
            }
        }
        //初始化结局纪录节点
        cc.resources.load("Prefabs/结局节点", cc.Prefab, (err, event) => {
            if (err) console.log("没有找到结局节点预制体");
            for (let i = 0; i < GameManager.EndData.length; i++) {
                if (GameManager.EndData[i] == 1) {
                    let pre = cc.instantiate(event);
                    pre.setParent(GameManager.GetUINode("结局纪录/框"));
                    GameManager.Instance.LoadSpriteFrame("Sprits", "结局/" + Ending.EndName[i], (spf: cc.SpriteFrame) => {
                        pre.getChildByName("图片").getComponent(cc.Sprite).spriteFrame = spf;
                    })
                    pre.getChildByName("描述").getComponent(cc.Label).string = Ending.EndName[i];
                }
            }

        })
        let endnum: number = 0;
        for (let i of GameManager.EndData) {
            if (i == 1) {
                endnum++;
                if (endnum >= 4) {//小结局达成超过4个,显示领养框关闭按钮
                    GameManager.GetUINode("StarPanel/领养框/关闭").active = true;
                    return;
                }
            }
        }

        //测试
        // GameManager.GetUINode("StarPanel/领养框/关闭").active = true;
    }


    //鲨鱼讲话
    SharkSay(VoiceIndex: number[], callback?: Function) {
        this.GamePause = true;
        if (VoiceIndex.length == 0) {//完成
            this.GamePause = false;
            GameManager.GetUINode("鲨鱼台词").active = false;
            if (callback) callback();
        } else {//没有完成继续读
            let Text: string = this.SayDate.json[VoiceIndex[0]].SayDate;
            let AnimaName: string = this.SayDate.json[VoiceIndex[0]].animation;
            BundleManager.GetBundle("AudioClips").load(Text, cc.AudioClip, (err, event) => {
                let AUDIOID;
                if (err) {
                    console.log("没有找到音频文件:" + Text);
                    AUDIOID = cc.audioEngine.playEffect(this.defaultaudio, false);
                } else {
                    AUDIOID = cc.audioEngine.playEffect(event, false);
                }
                GameManager.GetUINode("鲨鱼台词").active = true;
                GameManager.GetUINode("鲨鱼台词").getComponent(cc.Label).string = Text;
                this.SharkSetAnimation(AnimaName);
                VoiceIndex.splice(0, 1);
                cc.audioEngine.setFinishCallback(AUDIOID, () => {
                    if (this.sharkData[10] == 0) {
                        this.SharkSetAnimation("默认笑");
                    } else {
                        this.SharkSetAnimation("默认皱眉");
                    }
                    this.SharkSay(VoiceIndex, callback);
                });
            })
            this.SharkAction(VoiceIndex[0]);
        }
    }
    //设置鲨鱼动画(表情)
    SharkSetAnimation(AnimationName: string) {
        this.SharkNode.getComponent(cc.Animation).play(AnimationName);
    }


    SharkAction(sayid: number) {
        switch (sayid) {
            case 118:
            case 120:
            case 123:
                {
                    cc.tween(this.SharkNode)
                        .to(0.2, { position: cc.v3(this.SharkNode.x, this.SharkNode.y + 100) })
                        .to(0.2, { position: cc.v3(this.SharkNode.x, this.SharkNode.y) })
                        .union()
                        .repeat(3)
                        .start()
                }
                break;
            case 133:
                {
                    GameManager.GetUINode("EndTalk").getComponent(EndTalk).sharkTween(0.8, 2, 0.08);
                    GameManager.Instance.LoadSpriteFrame("Sprits", "最终结局/真结局放手", (spf) => {
                        let shark = GameManager.GetUINode("EndTalk/鲨鱼");
                        shark.getComponent(cc.Sprite).spriteFrame = spf;
                        shark.setPosition(shark.x + 50, shark.y);
                        let face = GameManager.GetUINode("EndTalk/鲨鱼/脸");
                        face.setPosition(face.x - 50, face.y);
                    })
                }
                break;
            case 135:
                {
                    GameManager.GetUINode("EndTalk").getComponent(EndTalk).sharkTween(1, 0, 0.05);
                    GameManager.GetUINode("EndTalk/伤心背景").active = true;
                }
                break;
        }
    }


    //关灯之后的事件
    Onblackroom() {
        this.sharkData[7] = 1;
        if (this.sharkData[5] == 1) {//身上带花
            this.sharkData[6] = 1;
            this.SharkSay([74]);
            this.LoadSharkSprite("身体/寄生").then((spf: cc.SpriteFrame) => {
                GameManager.GetNode("room/小鲨鱼").getComponent(cc.Sprite).spriteFrame = spf;
            })
        } else {
            this.fear();
        }
    }
    //开灯之后的事件
    OnExitblackroom() {
        if (this.sharkData[6] == 1) {//被花吃了
            EndingAnimation.PlayEndingAnimation(8);
        } else {
            this.sharkData[8] = 1;
        }
        if (this.sharkData[9] == 1) {//吓无用鲨鱼
            EndingAnimation.PlayEndingAnimation(4);
        }
    }

    //前往户外后的事件
    Onoutdoorincident() {
        GameManager.GetUINode("道具框/灯亮").active = true;
    }
    //户外回房间后的事件
    OnoutdoorToroomincident() {
        //暂无
        GameManager.GetNode("room").active = true;
        GameManager.GetUINode("回房").active = false;
        this.SetPropBoxActive(true);
        this.cb && this.cb();
    }
    //设置道具框的显示与隐藏
    SetPropBoxActive(IsLook: boolean) {
        this.UINode.getChildByName("道具框").active = IsLook;
    }

    //设置鲨鱼大小
    ChanggeSharkSize(size: number) {
        this.SharkNode.getComponent(Tween_breathe).TweenId.stop();
        let Size = 1.2 + (size * 0.34);//缩放大小
        if (Size > 3.9) Size = 3.9;

        if (size >= 7) {
            GameManager.GetUINode("道具框/哑铃").active = false;
            GameManager.GetUINode("道具框/垃圾桶").active = false;
        }
        if (size >= 8) {
            this.LoadSharkSprite("身体/胖鲨" + size).then((date: cc.SpriteFrame) => {
                this.SharkNode.getComponent(cc.Sprite).spriteFrame = date;
                this.SharkNode.getComponent(Tween_breathe).enabled = false;
            });
        }
        if (size == 10) {
            EndingAnimation.PlayEndingAnimation(1);
        }
        this.SharkNode.scale = Size;
        if (size < 8) {
            this.SharkNode.getComponent(Tween_breathe).resetTween(Size);
        }
        this.sharkData[0] = size;
    }
    //点击领养
    OnAdoptClick() {
        if (!Banner.IsBlackWhite) {//正常包模式
            Banner.Instance.ShowNativeAd();
        } else {//黑白包模式
            if (Banner.cityIswhite) {//黑包
                Banner.Instance.ShowNativeAd();
            } else {//白包
                Banner.Instance.ShowNativeAd();
            }
        }
        GameManager.GetUINode("StarPanel").active = false;
        if (GameManager.SharkHurted) {
            this.SharkSay([40]);
        }
        else {
            this.SharkSay([0, 1]);
        }
    }
    private NoAdoptNum: number = 0;//点击不领养的次数
    //开始界面点击不领养
    OnNoAdoptClick() {
        this.NoAdoptNum++;
        if (this.NoAdoptNum < 5) {
            let randomX: number = Math.random() * 300 + 100;
            let randomY: number = Math.random() * 500 - 150;
            WTool.Tween_to(GameManager.GetUINode("StarPanel/领养框/不要"), cc.v2(randomX, randomY), 0.5, "");
        } else {
            this.NoAdoptNum = 0; //弹出选择放弃
            GameManager.GetUINode("StarPanel/领养框").active = false;
            GameManager.GetUINode("StarPanel/放弃框").active = true;
        }
    }
    //点击大胖鲨按钮
    OnBigSharkClick() {
        this.SharkNode.getComponent(Tween_breathe).TweenId.stop();
        GameManager.GetNode("room/胖胖鲨按钮").active = false;
        EndingAnimation.PlayEndingAnimation(2);
    }
    //点击放弃领养
    OnAbandonClick() {
        if (GameManager.GetNode("outdoor/流浪鲨鱼").active) {
            GameManager.Instance.SharkNode.active = false;
            GameManager.GetUINode("道具框/苹果").active = false;
            GameManager.GetUINode("道具框/出门").active = true;
            GameManager.GetUINode("StarPanel").active = false;
        }
        else {
            EndingAnimation.PlayEndingAnimation(11);
        }
    }
    //点击取消放弃领养
    OnNoAbandonClick() {
        GameManager.GetUINode("StarPanel/放弃框").active = false;
        GameManager.GetUINode("StarPanel/领养框").active = true;
        GameManager.GetUINode("StarPanel/领养框/不要").position = cc.v3(200, -350);
    }

    //点击关闭领养框
    OnCloseBtnClick() {
        GameManager.GetUINode("鲨鱼台词").setPosition(0, -280);
        this.SharkNode = GameManager.GetUINode("StarPanel/小鲨鱼");
        console.log(this.SharkNode)
        cc.tween(GameManager.GetUINode("StarPanel/领养框"))
            .to(1, { position: cc.v3(0, -(cc.view.getVisibleSize().height / 2 + 300)) })
            .call(() => {
                this.SharkSay([118, 119, 120, 121, 122, 123, 124, 125, 126], () => {
                    GameManager.Instance.LoadPrefab("EndTalk", (pre) => {
                        let endtalk = cc.instantiate(pre);
                        endtalk.getComponent(EndTalk).Init();
                    })
                });
            })
            .start()
    }

    public static GetNode(path: string): cc.Node {
        return cc.find(path, GameManager.Instance.GameNode);
    }
    public static GetUINode(path: string): cc.Node {
        return cc.find(path, GameManager.Instance.UINode);
    }

    public Tantalizeindex: number = 0;//吊胃口进度
    //吊胃口
    Tantalize() {
        this.scheduleOnce(() => {
            if (this.sharkData[4] == 0) {
                if (this.Tantalizeindex == 10) {
                    this.sharkData[4] = 1;
                    EndingAnimation.PlayEndingAnimation(3);
                }
                this.SharkSay(SharkSayManager.GetSharkSayDate(SharkSayType.吊胃口), () => {
                    this.Tantalizeindex++;
                    this.Tantalize();
                })
            }
        }, 6)
    }
    public fearindex: number = 0;//害怕进度
    //关灯后的害怕
    fear() {
        this.scheduleOnce(() => {
            if (this.sharkData[8] == 0) {
                this.SharkSay(SharkSayManager.GetSharkSayDate(SharkSayType.害怕), () => {
                    if (this.fearindex == 10) {
                        this.sharkData[9] = 1;
                        return;
                    }
                    this.fearindex++;
                    this.fear();
                })
            }
        }, 6)
    }

    ShowOverPanel(isbad: boolean) {
        GameManager.GetUINode("OverPanel").setSiblingIndex(999);
        const gg = () => {
            if (!Banner.IsBlackWhite) {//正常包模式
                Banner.Instance.ShowNativeAd();
            } else {//黑白包模式
                if (Banner.cityIswhite) {//黑包
                    Banner.Instance.ShowNativeAd();
                    Banner.Instance.ShowVideo(() => { });
                } else {//白包
                    Banner.Instance.ShowNativeAd();
                }
            }
        }

        if (!isbad) {
            //好结局
            let end = GameManager.GetUINode("OverPanel/好结局");
            end.opacity = 0;
            WTool.Tween_Opacity(end, 1, 0, 255, () => {
                WTool.Tween_to(end.getChildByName("描述"), cc.v2(0, 100), 2, "", () => {
                    this.scheduleOnce(() => {
                        gg();
                        GameManager.GetUINode("OverPanel/返回主页").active = true;
                        cc.tween(GameManager.GetUINode("OverPanel/返回主页"))
                            .to(1.25, { scaleX: -1.04, scaleY: 1.04 })
                            .to(1.25, { scaleX: -1, scaleY: 1 })
                            .union()
                            .repeatForever()
                            .start();
                    }, 2)
                })
            })
        }
        else {
            //坏结局
            let endbg = GameManager.GetUINode("OverPanel/坏结局/背景");
            endbg.opacity = 0;
            endbg.parent.active = true;
            WTool.Tween_Opacity(endbg, 1, 0, 255, () => {
                WTool.Tween_to(endbg.parent.getChildByName("描述"), cc.v2(0, 0), 2, "", () => {
                    this.scheduleOnce(() => {
                        gg();
                        GameManager.GetUINode("OverPanel/返回主页").active = true;
                        cc.tween(GameManager.GetUINode("OverPanel/返回主页"))
                            .to(1.25, { scaleX: -1.04, scaleY: 1.04 })
                            .to(1.25, { scaleX: -1, scaleY: 1 })
                            .union()
                            .repeatForever()
                            .start();
                    }, 2)
                })
            })
        }
    }

    GetEndingIsFinish(end: End) {//初始化数据存储
        return GameManager.EndData[BundleManager.GetEnumValues(End).indexOf(end)];
    }
    SetEndingFinish(end: string, value: number) {//存入本地数据
        GameManager.EndData[BundleManager.GetEnumValues(End).indexOf(end)] = value;
    }

    LoadPrefab(path: string, callback) {
        cc.resources.load("Prefabs/" + path, cc.Prefab, (err, res: cc.Prefab) => {
            if (err) console.log(err);
            callback(res);
        })
    }
    LoadSpriteFrame(bundle: string, path: string, callback) {
        BundleManager.GetBundle(bundle).load(path, cc.SpriteFrame, (err, res: cc.SpriteFrame) => {
            if (err) console.log(err);
            callback(res);
        })
    }

    GetEnumKey(Em: any, value) {
        for (const key in Em) {
            if (Em[key] === value) {
                return key;
            }
        } return undefined;
    }
    //加载鲨鱼图片资源
    LoadSharkSprite(path: string) {
        return new Promise((resolve, reject) => {
            BundleManager.GetBundle("SharkSprite").load(path, cc.SpriteFrame, (err, res: cc.SpriteFrame) => {
                if (err) {
                    if (reject) {
                        console.log("没有发现资源" + path);
                    }
                }
                if (resolve) {
                    resolve(res);
                }
            })
        });

    }


    //打开暂停界面
    Open_PausePanel() {
        if (!Banner.IsBlackWhite) {//正常包模式
            Banner.Instance.ShowNativeAd();
        } else {//黑白包模式
            if (Banner.cityIswhite) {//黑包
                Banner.Instance.ShowNativeAd();
            } else {//白包
                Banner.Instance.ShowNativeAd();
            }
        }
        GameManager.GetUINode("暂停界面").active = true;

    }
    //退出暂停界面
    Exit_PausePanel() {
        GameManager.GetUINode("暂停界面").active = false;

    }
    //点击提示按钮
    OnTipClick() {
        Banner.Instance.ShowVideo(() => {
            GameManager.GetUINode("结局描述").active = true;
        })
    }
    //返回主页
    ReMian() {
        cc.director.loadScene("MainPanel");

    }
}
